package com.controller;

import com.domain.Blog;
import com.domain.Comment;
import com.service.BlogService;
import com.service.CommentService;
import com.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Service
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private CommentService commentService;
    @Resource
    private BlogService blogService;
    @RequestMapping("/save.do")
    private String save(Comment comment, @RequestParam("imageCode")String imageCode, HttpServletResponse response, HttpServletRequest request, HttpSession session) throws IOException {
String sRand= (String) session.getAttribute("sRand");
        JSONObject result=new JSONObject();
        int resTotal=0;
        if(!imageCode.equals(sRand)){
            result.put("success",Boolean.FALSE);
            result.put("errorInfo","验证码错误");
        }else {
            String userIp=request.getRemoteAddr();
            comment.setUserIp(userIp);
            if(comment.getId()==null){
                resTotal=commentService.add(comment);
                Blog blog=blogService.findById(comment.getBlog().getId());
                blog.setReplyHit(blog.getReplyHit()+1);
                blogService.update(blog);
            }
        }
        if (resTotal>0){
            result.put("success",Boolean.TRUE);
        }else {
            result.put("success",Boolean.FALSE);
        }
        ResponseUtil.write(response,result);
        return null;
    }
}
